package gui;

import javax.swing.JOptionPane;

import castlewarserver.Connector;

public class ConnectionThread implements Runnable{

	ConnectionMenu connection;


	public ConnectionThread (ConnectionMenu connection){
		this.connection=connection;
	}

	@Override
	public void run() {

		String player= (String) connection.comboBox.getSelectedItem();
		Connector gameConnector = new Connector(connection.textField.getText());
		gameConnector.resetGame();
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		if (gameConnector.connectionError){
			connection.connectButton.setEnabled(true);
		}
		else if (gameConnector.isPalyerTaken(player)){
			JOptionPane.showMessageDialog(connection, "Player "+ player+" is taken. Please choose another one.");
			connection.connectButton.setEnabled(true);
		}
		else{
			while(true){

				String respond = gameConnector.newGame(player);
				if(gameConnector.connectionError){
					break;
				}
				if (respond != null){
					if(respond.equalsIgnoreCase("BOTH")){
						// open main window
						MainWindow mainWindow = new MainWindow(player,connection.textField.getText());
						connection.dispose();
						break;
					}

					else if (respond.equalsIgnoreCase(player)){
						connection.lblAwaiting.setVisible(true);
						connection.progressBar.setVisible(true);

					}
				}

				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}


	}

}
